//
//  CCAPublicModel.m
//  Activity
//
//  Created by its on 15/5/11.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCAPublicModel.h"
#import <AVOSCloud/AVOSCloud.h>
#import <RXPromise/RXPromise.h>
#import <RXPromise/RXPromise+RXExtension.h>
#import "CCError.h"

@implementation CCAPublicModel

- (id) init {
  if (self = [super init]) {
  }
  return self;
}
- (RACSignal *) publicActivity {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    NSMutableArray *promiseArrary = [NSMutableArray array];
    for (UIImage *image in self.imageArray) {
      AVFile *file = [AVFile fileWithData:UIImageJPEGRepresentation(image, 1)];
      RXPromise *promise =  [[RXPromise alloc] init];
      [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        NSLog(@"file: %@, url: %@ bucket: %@", file.objectId, file.url, file.bucket);
        if (succeeded) {
          [promise resolveWithResult:file.url];
        } else {
          [promise rejectWithReason:[CCError errorWithCode:1 des:@"图片发布失败"]];
        }
      }];
      [promiseArrary addObject: promise];
    }
    RXPromise *objpromise = [RXPromise all: promiseArrary].then(^id(NSArray *result) {
      AVObject *object = [AVObject objectWithClassName:@"activity"];
      [object setObject:self.title forKey:@"title"];
      [object setObject:[NSString stringWithFormat:@"%@-%@",self.startDate, self.endDate] forKey:@"time"];
      [object setObject:self.money forKey:@"money"];
      [object setObject:self.people forKey:@"people"];
      [object setObject:self.content forKey:@"content"];
      [object setObject:self.address forKey:@"address"];
      [object setObject:result forKey:@"images"];
      [object setObject:[AVUser currentUser] forKey:@"author"];
      [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
          [subscriber sendNext:[CCError errorWithCode:0 des:@"活动发布成功"]];
        } else {
          [subscriber sendNext:[CCError errorWithCode:1 des:@"活动发布失败"]];
        }
      }];
      return nil;
    }, ^id (id error) {
      [subscriber sendNext:error]; //
      return nil;
    });

    return [RACDisposable disposableWithBlock:^{
      for (RXPromise *promise in promiseArrary) {
        [promise cancel];
      }
      [objpromise cancel];
    }];
  }];
}

- (void) test {
  UIImage *image = [UIImage imageNamed:@"psb.jpeg"];
  UIImage *image1 = [UIImage imageNamed:@"man"];
  UIImage *image2 = [UIImage imageNamed:@"selected"];
  _imageArray = @[image, image1,image2];
  _title = @"测试程序";
  _startDate = @"15.12.11";
  _endDate = @"16.01.01";
  _money = @"11";
  _people = @"1555";
  _content = @"这是一个测试程序";
  _address = @"清华信息港A座501";
}
@end
